# -*- coding: utf-8 -*-
# @File:     dialog.py
# @Author:
# @DateTime: 2025/10/16/11:26

import datetime
import json
import time
from typing import Optional, Union, Any, List, Dict
from fastapi.encoders import jsonable_encoder
from sqlalchemy import or_
from sqlalchemy.orm import Session

from app.db.database import get_db
from app.models.system import Users
from app.utils import security
from app.utils.custom_exc import CustomException
from app.utils.custom_response import success_response, error_response
from fastapi import APIRouter, Query, Body, Path, Depends, UploadFile, Form, File, Request
from pydantic import BaseModel, Field

from app.models.chat import Dialog, DialogHistory
from app.utils.curd_base import ModelCRUD
from app.utils.file_storage import get_storage_file, save_storage_file, delete_storage_file
from app.utils.utils import get_now_time_string

router = APIRouter()


class CRUDDialog(ModelCRUD):

    model = Dialog


class CRUDDialogHistory(ModelCRUD):

    model = DialogHistory


class ResDialog(BaseModel):
    id: int = Field(description='用户')
    dialog_uid: Optional[str] = Field(default=None, description='对话UID')
    agent_type: Optional[str] = Field(default=None, description='对话Agent类型')


able_filter_list = [
    {'name': 'user_id', 'source_filed': 'user_id', 'lookup_expr': 'eq', 'label': '等于user', 'type': int, 'method': None, 'required': True},
    {'name': 'agent_type', 'source_filed': 'agent_type', 'lookup_expr': 'eq', 'label': '等于agent_type', 'type': str, 'method': None, 'required': False},
]


@router.get("/dialog", summary="获取对话记录", response_model=ResDialog, name='获取对话记录')
async def user_membership(
    *,
    db: Session = Depends(get_db),
    page: int = Query(1, description='页码', ge=1),
    page_size: int = Query(10, description='页面大小', le=50, ge=1),
    agent_type: str = Query(None, description='对话类型'),
    current_user: Users = Depends(security.verify_access_token),
) -> Any:
    order_by_fields = ('-id',)
    crud = CRUDDialog()
    crud_history = CRUDDialogHistory()

    req_data = {
        'user_id': current_user.id,
    }
    if agent_type:
        req_data['agent_type'] = agent_type
    queryset, total = crud.get_page_queryset(db, page=page, page_size=page_size, req_data=req_data, able_filter_list=able_filter_list, order_by_fields=order_by_fields)
    only = ('id', 'dialog_uid', 'agent_type', 'create_time')
    history_only = ('id', 'dialog_id', 'role', 'content')
    li = []
    for instance in queryset:
        data = instance.to_dict(only=only, datetime_format='%Y-%m-%d %H:%M:%S')
        history_queryset = db.query(DialogHistory).filter(DialogHistory.dialog_id == int(instance.id))
        history_queryset = crud_history.order_by(history_queryset, ('id', ))
        history_li = []
        for result_ins in history_queryset:
            result_data = result_ins.to_dict(only=history_only, datetime_format='%Y-%m-%d %H:%M:%S')
            history_li.append(result_data)

        data['history_list'] = history_li
        li.append(data)
    resp = {
        "list": li,
        'total': total
    }
    return success_response(data=resp)


class DeleteModel(BaseModel):
    id: list[int] = Field(description='ID列表')


@router.delete("/dialog", summary="删除对话", response_model=ResDialog, name='删除对话')
async def delete_role(
    *,
    db: Session = Depends(get_db),
    req_data: DeleteModel,
    current_user: Users = Depends(security.verify_access_token),
) -> Any:
    req_body = jsonable_encoder(req_data)
    id_list = req_body.get('id', [])
    queryset = db.query(Dialog).filter(Dialog.id.in_(id_list), Dialog.user_id == int(current_user.id))

    queryset.delete()
    db.commit()
    return success_response(data={})
